package cn.kys.common.utils;


import org.apache.catalina.startup.Catalina;
import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Encoder;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.List;

public class LittleTools {

    private static int Epsg = 4326;

    /**
     * 根据原始表名、日期以及年月日之间的分隔符，获取当天的表名
     *
     * @param sTableName
     * @param sDate
     * @param sSplit
     * @return
     */
    public static String GetCurrentTableName(String sTableName, String sDate, String sSplit) {
        String sTemp = sDate.replace(sSplit, "");
        return sTableName + sTemp;
    }

    /**
     * 判断给定的日期是否为今天的日期
     *
     * @param sDate
     * @return
     */
    public static boolean IsToday(String sDate) {
        Calendar calTemp = Calendar.getInstance();
        String[] sArray = sDate.split("-");
        calTemp.set(Integer.parseInt(sArray[0]), Integer.parseInt(sArray[1]) - 1, Integer.parseInt(sArray[2]));
        Date dTemp = calTemp.getTime();

        if (3 != sArray.length) return false;
        //当前日期
        Calendar calCurrent = Calendar.getInstance();
        calCurrent.setTime(new Date());
        Date dCurrentDay = calCurrent.getTime();

        SimpleDateFormat sp = new SimpleDateFormat("yyyyMMdd");
        String sTemp = sp.format(dTemp);
        String sCurrentDay = sp.format(dCurrentDay);


        return sCurrentDay.equals(sTemp);
    }

    public static String CreateBatchInsertSql(List<String> listValues, String sInsert) {
        if (listValues.size() == 0) return "";
        String sSql = String.format("%s %s", sInsert, listValues.get(0));
        for (int i = 1; i < listValues.size(); i++) {
            sSql += String.format(", %s", listValues.get(i));
        }
        return sSql;
    }


    public static String SqlOrList(List<String> listIds, String sField) {
        if (listIds.size() == 0) return "";
        String sSql = String.format("%s = %s", sField, listIds.get(0));
        for (int i = 1; i < listIds.size(); i++) {
            sSql += String.format(" OR %s = %s", sField, listIds.get(i));
        }
        return sSql;
    }

    public static String ConnectMultiPolygonSql1(List<String> listPolygon) {
        if (0 == listPolygon.size()) return "";
        String sSql = "MULTIPOLYGON(";

        sSql += String.format("%s", listPolygon.get(0).replace("POLYGON", ""));
        for (int i = 1; i < listPolygon.size(); i++) {
            String sTemp = listPolygon.get(i).toString();
            sTemp = sTemp.replace("POLYGON", "");
            sSql += String.format(",%s", sTemp);
        }
        sSql += ")";
        return sSql;
    }

    public static String ConnectMultiPolygonSql(List<String> listPolygon) {
        if (0 == listPolygon.size()) return "";
        String sSql = "POLYGON(";
        sSql += String.format("%s", listPolygon.get(0));
        for (int i = 1; i < listPolygon.size(); i++) {
            sSql += String.format(",%s", listPolygon.get(i));
        }
        sSql += ")";
        return sSql;
    }

    public static String PtRemoveZComponent(String pt_str, String sComponentSplitSymbol) {
        String[] arrComponent = pt_str.split(sComponentSplitSymbol);
        if (arrComponent.length < 2) return "";
        else {
            String sTemp = arrComponent[0] + " " + arrComponent[1];
            return sTemp;
        }
    }

    /**
     * 原始的polygon_str去除z坐标
     *
     * @param polygon_str
     * @param sPolygonSplitSymbol
     * @param sPtSplitSymbol
     * @param sComponentSplitSymbol
     * @return
     */
    public static List<String> RemoveZComponent(String polygon_str, String sPolygonSplitSymbol, String sPtSplitSymbol,
                                                String sComponentSplitSymbol) {
        List<String> listData = new ArrayList<>();
        String[] arrayPolygon = polygon_str.split(sPolygonSplitSymbol);
        for (String sPolygon : arrayPolygon) {
            String sNewPolygon = "";
            String[] arrPt = sPolygon.split(sPtSplitSymbol);
            if (arrPt.length < 4) continue;
            sNewPolygon += PtRemoveZComponent(arrPt[0], sComponentSplitSymbol);
            for (int i = 1; i < arrPt.length; i++) {
                sNewPolygon += String.format(",%s", PtRemoveZComponent(arrPt[i], sComponentSplitSymbol));
            }
            listData.add(sNewPolygon);
        }
        return listData;
    }

    public static String String2Polyline(String str, String splitSymbol) {
//        String[] sTemp = str.split(splitSymbol);
        List<String> listPolygon = RemoveZComponent(str, splitSymbol, ",", " ");

        String sValue = null;

        if (0 == listPolygon.size()) {
            return null;
        } else if (1 == listPolygon.size()) {
            sValue = String.format("ST_LineFromText('LINESTRING (%s)', %d)", listPolygon.get(0), Epsg);
        } else {
            sValue = String.format("ST_MultiLineFromText('MULTILINESTRING( (%s)", listPolygon.get(0));
            for (int i = 1; i < listPolygon.size(); i++) {
                sValue += String.format(", (%s)", listPolygon.get(i));
            }
            sValue += String.format(")', %d)", Epsg);
        }
        return sValue;
    }


    /**
     * 前台传入的几何图形字符串转成sql语句
     *
     * @param str:         前台传入的几何图形字符串
     * @param splitSymbol: 多个几何图像之间的分隔符
     * @return
     */
    public static String String2Polygon(String str, String splitSymbol) {
//        String[] sTemp = str.split(splitSymbol);
        List<String> listPolygon = RemoveZComponent(str, splitSymbol, ",", " ");

        String sValue = null;
//        if (1 == sTemp.length)
//        {
//            sValue = String.format("ST_GeomFromText('POLYGON((%s))', %d)", str, Epsg);
//        }
//        else
//        {
        sValue = "ST_GeomFromText('POLYGON (" + String.format("(%s)", listPolygon.get(0));
        for (int i = 1; i < listPolygon.size(); i++) {
            sValue += String.format(", (%s)", listPolygon.get(i));
        }
        sValue += String.format(")', %d)", Epsg);
//        }
        return sValue;
    }

    /**
     * 将MultipartFile 图片文件编码为base64
     *
     * @param file
     * @return
     * @throws Exception
     */
    public static String generateBase64(MultipartFile file) {
        if (file == null || file.isEmpty()) {
            return "";
//            throw new RuntimeException("图片不能为空！");
        }
        String fileName = file.getOriginalFilename();
        String fileType = fileName.substring(fileName.lastIndexOf("."));
        String contentType = file.getContentType();
        byte[] imageBytes = null;
        String base64EncoderImg = "";
        try {
            imageBytes = file.getBytes();
            BASE64Encoder base64Encoder = new BASE64Encoder();
            /**
             * 1.Java使用BASE64Encoder 需要添加图片头（"data:" + contentType + ";base64,"），
             *   其中contentType是文件的内容格式。
             * 2.Java中在使用BASE64Enconder().encode()会出现字符串换行问题，这是因为RFC 822中规定，
             *   每72个字符中加一个换行符号，这样会造成在使用base64字符串时出现问题，
             *   所以我们在使用时要先用replaceAll("[\\s*\t\n\r]", "")解决换行的问题。
             */
            base64EncoderImg = "data:" + contentType + ";base64," + base64Encoder.encode(imageBytes);
            base64EncoderImg = base64EncoderImg.replaceAll("[\\s*\t\n\r]", "");
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return base64EncoderImg;
    }

    public static List<File> GetAllFilesinDir(String sDir) {
        File dirFile = new File(sDir);

        if (Objects.isNull(dirFile) || !dirFile.exists() || dirFile.isFile())
            return null;

        File[] childrenFiles = dirFile.listFiles();
        if (Objects.isNull(childrenFiles) || childrenFiles.length == 0)
            return null;

        List<File> files = new ArrayList<>();
        for (File childFile : childrenFiles) {
            // 如果是文件，直接添加到结果集合
            if (childFile.isFile()) {
                files.add(childFile);
            }
        }
        return files;
    }

    public static String encodeBase64File(File file) {
        try {
            FileInputStream inputFile = new FileInputStream(file);
            byte[] buffer = new byte[(int) file.length()];
            inputFile.read(buffer);
            inputFile.close();
            return new BASE64Encoder().encode(buffer);
        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;
    }

    /**
     * 将图片转换成Base64编码
     *
     * @param imgFile 待处理图片地址
     * @return
     */
    public static String getImgBase(String imgFile) {

        // 将图片文件转化为二进制流
        InputStream in = null;
        byte[] data = null;
        // 读取图片字节数组
        try {
            in = new FileInputStream(imgFile);
            data = new byte[in.available()];
            in.read(data);
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 图片头
        //String imghead = "data:image/jpeg;base64,";
        return Base64.getEncoder().encodeToString(data);
    }


    public static void base64ToFile(String destPath, String base64, String fileName) {
        File file = null;
        //创建文件目录
        String filePath = destPath;
        File dir = new File(filePath);
        if (!dir.exists() && !dir.isDirectory()) {
            dir.mkdirs();
        }
        BufferedOutputStream bos = null;
        FileOutputStream fos = null;
        try {
            byte[] bytes = Base64.getDecoder().decode(base64);
            file = new File(filePath + "/" + fileName);
            fos = new FileOutputStream(file);
            bos = new BufferedOutputStream(fos);
            bos.write(bytes);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (bos != null) {
                try {
                    bos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static String GenerateImageWithName(String sImgBase64, int imgH, int imgW, String sName) {

        int spanWidth = 4;

        int imageWidth = sName.length() * 22 + 4 + imgW + spanWidth;  //图片的宽度
        int imageHeight = 20 < imgH ? imgH : 20; //图片的高度


        BufferedImage image = new BufferedImage(imageWidth, imageHeight, BufferedImage.TYPE_INT_ARGB);
        //设置图片的背景色
//        Graphics2D main = image.createGraphics();
//        main.setColor(Color.white);
//        main.fillRect(0, 0, imageWidth+4, imageHeight);
        //***********************设置下面的提示框
        int tempSpan = (imgH - 20) / 2;
        Graphics2D tip = image.createGraphics();
        //tip.setColor(new Color(100, 100, 100, 0));
        //绘制图片
        byte[] imageBytes = Base64.getDecoder().decode(sImgBase64);
//        BufferedImage img = null;
        Image img = null;
        try {
            img = ImageIO.read(new ByteArrayInputStream(imageBytes));
//            img = ImageIO.read(new ByteArrayInputStream(imageBytes));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        tip.drawImage(img, 0, 0, null);

        //设置区域颜色
//        tip.setColor(new Color(72, 126, 255));
        tip.setColor(new Color(100, 100, 100, 255));

        //填充区域并确定区域大小位置
        tip.fillRect(2 + imgW, 0, imageWidth - imgW, imageHeight);


        //设置字体颜色，先设置颜色，再填充内容
        tip.setColor(new Color(255, 255, 255, 255));
        //设置字体
        Font tipFont = new Font("宋体", Font.BOLD, 20);
        tip.setFont(tipFont);

        tip.drawString(sName, 4 + 3 + imgW, 16 + tempSpan);


        //将图片转换陈字符串给前端
        String base64 = null;
        try {
            ByteArrayOutputStream stream = new ByteArrayOutputStream();
            ImageIO.write(image, "png", stream);
            base64 = new String(Base64.getEncoder().encode(stream.toByteArray()));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return base64;
    }

    public static String calAlertInOneMonth(String month) {

        String conditionMonth = "";
        String startMonth = "";
        String endMonth = "";
        if (!"".equals(month) && null != month) {

            Date date = new Date();

            int monthInt = Integer.parseInt(month);
            String monthStr = String.valueOf(monthInt);

            int nextMonth = monthInt + 1;
            String nextMonthStr = String.valueOf(nextMonth);

            if (monthInt < 10) {
                monthStr = "0" + String.valueOf(monthInt);
                nextMonthStr = "0" + String.valueOf(nextMonth);
            }

            String startPattern = "yyyy-" + monthStr + "-01 00:00:00";
            SimpleDateFormat sdf1 = new SimpleDateFormat(startPattern);

            String endPattern = "yyyy-" + nextMonthStr + "-01 00:00:00";
            SimpleDateFormat sdf2 = new SimpleDateFormat(endPattern);

            startMonth = sdf1.format(date);
            endMonth = sdf2.format(date);

            if (month.equals("12")) {
                endPattern = "yyyy-12-31 24:00:00";
                SimpleDateFormat sdf3 = new SimpleDateFormat(endPattern);
                endMonth = sdf3.format(date);
            }
        } else {
            return "";
        }
        //如果是12月，需要注意下

        conditionMonth = " and (pla.alert_time > '" + startMonth + "'" + " and pla.alert_time < '" + endMonth + "')";
        return conditionMonth;
    }

    //添加计算某天案件数的条件
    public static String calAlertInOneDay(String month, String dateNum) {

        String conditionMonth = "";
        String startMonth = "";
        String endMonth = "";
        if (!"".equals(dateNum) && null != dateNum) {
            Date date = new Date();

            String startPattern = "yyyy-" + month + "-" + dateNum + " 00:00:00";
            SimpleDateFormat sdf1 = new SimpleDateFormat(startPattern);

            String endPattern = "yyyy-" + month + "-" + dateNum + " 24:00:00";
            SimpleDateFormat sdf2 = new SimpleDateFormat(endPattern);

            startMonth = sdf1.format(date);
            endMonth = sdf2.format(date);

        } else {
            return "";
        }

        conditionMonth = " and (pla.alert_time > '" + startMonth + "'" + " and pla.alert_time < '" + endMonth + "')";
        return conditionMonth;
    }

    public static String getPorjectPath() {
        String rootPath = "";
        //windows下
        if ("\\".equals(File.separator)) {
            rootPath = System.getProperty("user.dir");
        }
        //linux下
        if ("/".equals(File.separator)) {
            rootPath = System.getProperty("catalina.home");
        }
        return rootPath;
    }


    public static String getTomcatAddress() throws UnknownHostException {
        Catalina catalina = new Catalina(); // 创建Catalina对象

        String tomcatHomePath = System.getProperty("catalina.home"); // 获取Tomcat安装路径
        InetAddress localHost = InetAddress.getLocalHost(); // 获取本机IP地址

        int port = Integer.parseInt(System.getProperty("server.port")); // 获取Tomcat运行端口号

        String address = "http://" + localHost.getHostName() + ":" + port + "/"; // 构造Tomcat访问地址

        System.out.println("Tomcat地址为：" + address);
        return  address;
    }


}
